import { Module } from 'vuex'
import { IRootState } from '../types'
import { IProjectModuleState, IProjectState } from './types'
import { IDataType } from '@/render/service/types'

import {
  newProject,
  getAllProjects,
  getProjectModules,
  updateProjectModules,
  deleteProject,
  deleteProjectModule
} from '@/render/service/projects/projects'
import { generate } from '@/render/service/generate/generate'

const projectsModule: Module<IProjectState, IRootState> = {
  namespaced: true,
  state() {
    return {
      projectNames: new Set(),
      projects: [],
      projectModules: new Map()
    }
  },
  getters: {
    getAllProjects: (state) => {
      if (state.projects) {
        return state.projects
      }
    }
  },
  mutations: {
    ADD_PROJECT(state, val) {
      if (state.projectNames == null) {
        state.projectNames = new Set()
      }
      state.projectNames.add(val.id)
      if (state.projects == null) {
        state.projects = []
      }
      state.projects.push(val)
    },
    SET_ALL_PROJECTS(state, val) {
      if (state.projectNames == null) {
        state.projectNames = new Set()
      }
      state.projectNames.add(val.name)
      state.projects = val
    },
    UPDATE_PROJECT(state, project) {
      if (state.projects == null) {
        state.projects = []
      }
      const index = state.projects.findIndex(
        (item) => item.name === project.name
      )
      if (index !== -1) {
        state.projects.splice(index, 1, project)
      }
    },
    SET_PROJECTMODULES(state, project) {
      if (state.projectModules == null) {
        state.projectModules = new Map()
      }
      state.projectModules.set(project.name, project.allProjectModules)
    },
    DELETE_PROJECT(state, projectName) {
      const index = state.projects.findIndex(
        (item) => item.name === projectName
      )
      if (index >= 0) {
        state.projects.splice(index, 1)
      }
    },
    DELETE_PROJECTMODULE(state, { projectName, projectModuleName }) {
      for (let i = 0; i < state.projects.length; i++) {
        if (state.projects[i].name === projectName) {
          const index = state.projects[i].projectModules.findIndex(
            (item) => item.name === projectModuleName
          )
          if (index >= 0) {
            state.projects[i].projectModules.splice(index, 1)
          }
        }
      }
    }
  },
  actions: {
    createNewProject({ commit, state }, newproject) {
      console.log('createNewProject')
      return new Promise((resolve, reject) => {
        newProject(newproject)
          .then((res: any) => {
            const data = res.data
            commit('ADD_PROJECT', data)
            resolve(res.message)
          })
          .catch((err: any) => {
            reject(err)
          })
      })
    },
    loadProjects({ commit, state }) {
      return new Promise((resolve, reject) => {
        getAllProjects().then((res: IDataType) => {
          const data = res.data
          const length = data.length
          commit('SET_ALL_PROJECTS', data)
          resolve(data)
        })
      })
    },
    deleteProject({ commit, state }, projectName) {
      console.log(`删除工程 ${projectName} 信息`)
      return new Promise((resolve, reject) => {
        if (projectName == null) {
          reject('信息不全，删除失败')
        } else {
          deleteProject(projectName)
            .then((res: IDataType) => {
              commit('DELETE_PROJECT', projectName)
              resolve(res.message)
            })
            .catch((err: any) => {
              console.log(err)
            })
        }
      })
    },
    loadProjectModule({ commit, state }, projectName) {
      return new Promise((resolve, reject) => {
        if (state.projects && state.projects.length > 0) {
          const index = state.projects.findIndex(
            (item) => item.name === projectName
          )
          if (index > -1) {
            resolve(state.projects[index].projectModules)
          } else {
            reject([])
          }
        }
      })
    },
    updateProjectModules({ commit, state }, project) {
      return new Promise((resolve, reject) => {
        const addModuleIds = project.addProjectModules.join(',')
        const deleteModuleIds = project.deleteProjectModules.join(',')
        updateProjectModules(project.projectName, addModuleIds, deleteModuleIds)
          .then((res: IDataType) => {
            const data = res.data
            commit('UPDATE_PROJECT', data)
            resolve(res.message)
          })
          .catch((err: Error) => {
            console.log(err)
            reject(err)
          })
      })
    },
    deleteProjectModule({ commit, state }, { projectName, projectModuleName }) {
      console.log(`删除工程${projectName}下的${projectModuleName}模块`)
      return new Promise((resolve, reject) => {
        if (projectName == null || projectModuleName == null) {
          reject('信息不全，删除失败')
        } else {
          deleteProjectModule(projectName, projectModuleName)
            .then((res: IDataType) => {
              commit('DELETE_PROJECTMODULE', {
                projectName,
                projectModuleName
              })
              resolve(res.message)
            })
            .catch((err: Error) => {
              reject(err)
            })
        }
      })
    },
    generate(
      { commit, state },
      { projectName, projectModuleName, type, outputUrl }
    ) {
      console.log(
        `代码生成 ${projectName} ${projectModuleName} ${type} ${outputUrl} `
      )
      return new Promise((resolve, reject) => {
        generate(projectName, projectModuleName || '', type, outputUrl).then(
          (res: IDataType) => {
            resolve(res.message)
          }
        )
      })
    }
  }
}

export default projectsModule
